package cn.anecansaitin.whimsy.common.network;

import cn.anecansaitin.whimsy.Whimsy;
import cn.anecansaitin.whimsy.common.capabilities.battle.IBattleMode;
import cn.anecansaitin.whimsy.common.item.IBattleControllerSupplier;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
import net.neoforged.neoforge.network.handling.PlayPayloadContext;

public record BattleModeSwitchPack() implements CustomPacketPayload {
    public static final ResourceLocation ID = Whimsy.resource("battle_mode_switch_pack");

    public BattleModeSwitchPack(FriendlyByteBuf buf) {
        this();
    }

    @Override
    public void write(FriendlyByteBuf buffer) {
    }

    @Override
    public ResourceLocation id() {
        return ID;
    }

    public static void serverHandler(BattleModeSwitchPack pack, PlayPayloadContext context) {
        context.workHandler().submitAsync(() -> context.player().ifPresent((player) -> {
            IBattleMode battleMode = player.getCapability(IBattleMode.BATTLE_MODE);

            if (battleMode == null) {
                return;
            }

            if (battleMode.isInMode()) {
                battleMode.switchMode(player);
            } else if (player.getMainHandItem().getItem() instanceof IBattleControllerSupplier supplier && supplier.canSwitch(player)) {
                battleMode.setController(supplier.getBattleControllerId());
                battleMode.switchMode(player);
            }
        }));
    }
}
